<?php

namespace App\Http\Requests;


use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Urameshibr\Requests\FormRequest;

class PassengerUserRequest extends FormRequest
{


    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }


    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rule_action = 'getRulesBy'. ucfirst($this->getActionName());

        if(method_exists($this, $rule_action))
            return $this->$rule_action();

        return $this->getDefaultRules();
    }


    /**
     * 默认验证规则
     * @return array
     */
    protected function getDefaultRules()
    {
        return [];
    }


    /**
     * 设置信息 验证规则
     */
    protected function getRulesBySetInit()
    {
        return [

            'avatar'           => ['bail', 'required', 'max:150'],
            'nick_name'        => ['bail', 'required', 'max:20'],
            'password'         => ['bail', 'required', 'min:6', 'max:16'],
            'confirm_password' => ['bail', 'required', 'same:password']

        ];
    }


    /**
     * 修改信息验证
     */
    protected function getRulesByEdit()
    {
        return [
            'avatar'    => ['max:150'],
            'nick_name' => ['max:20'],
        ];
    }


    /**
     * 修改密码
     */
    protected function getRulesBySetPassword()
    {
        return [
            'old_password' => ['bail', 'required', function($attr, $value, $fail){
                if(!password_verify($value, Auth::user()->password)) {
                    $fail('原密码错误');
                }
            }],
            'new_password' => ['bail', 'required', 'min:6', 'max:16'],
            'confirm_password' => ['bail', 'required', 'same:new_password'],
        ];
    }



    protected function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(response()->json([
            'code' => 0,
            'msg'  => $validator->errors()->first()
        ]));
    }


    protected function getActionName()
    {
        return explode('@' , $this->route()[1]['uses'])[1];
    }


    public function attributes()
    {
        return [
            'avatar' => '头像',
            'nick_name' => '昵称',
            'password' => '密码',
            'old_password' => '原密码',
            'new_password' => '新密码',
            'confirm_password' => '重复密码',
        ];
    }


}
